package com.crane.framework.controller;

import com.crane.framework.response.CommonResult;
import com.crane.framework.service.IBpmnService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "流程操作 API")
@RestController
@RequestMapping("/api/v1.0/bpmn")
public class BpmnController {
  // 上传路径
  @Value("${crane.camunda.path}")
  private String path;

  // 通用的工作流操作api服务类
  @Resource private IBpmnService bpmnService;

  @Operation(summary = "上传流程文件")
  @PostMapping("/upload")
  public void uploadFile(MultipartFile file, String fileName, String name) throws Exception {
    // 上传并返回新文件名称
    InputStream is = file.getInputStream();
    File storageFile = new File(path + File.separator + fileName);
    FileOutputStream fos = new FileOutputStream(path + File.separator + fileName);
    byte[] buf = new byte[10 * 1024];
    int len = -1;
    while ((len = is.read(buf)) > -1) {
      fos.write(buf, 0, len);
    }
    fos.close();
    is.close();
    // 创建部署流程
    bpmnService.createDeploy(fileName, name, new FileSystemResource(storageFile));
  }

  // 根据流程定义id，启动流程；整个流程需要动态传2个参数（审批人），如果不传将会报错
  @Operation(summary = "启动流程")
  @GetMapping("/start/{processDefinitionId}")
  public CommonResult<String> startProcess(
      @PathVariable("processDefinitionId") String processDefinitionId) {
    Map<String, Object> variables = new HashMap<>();
    variables.put("uid", "1");
    variables.put("mid", "1000");
    bpmnService.startProcessInstanceAssignVariables(processDefinitionId, "AKF", variables);
    return CommonResult.success("流程启动成功");
  }
}
